package com.saascloud.restTemplate.core;

import com.saascloud.Constants;
import com.saascloud.core.saas.SaasContextUtil;
import com.saascloud.trace.TraceContext;
import com.saascloud.web.SaasWebUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @Author: liangxu
 * @Contact: one_dream@aliyun.com
 * @Date: 2022/5/30 15:44
 * @Version: 1.0
 * @Description:
 */
public class SaasRequestInteceptor implements ClientHttpRequestInterceptor {

    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
        HttpServletRequest httpServletRequest = SaasWebUtils.currentRequest();
        HttpHeaders headers = request.getHeaders();
        //传递traceid，用户token等
        headers.add(Constants.HttpHeader.TOKEN, httpServletRequest.getHeader(Constants.HttpHeader.TOKEN));
        headers.add(Constants.HttpHeader.TRACE_ID, TraceContext.getTrace());
        headers.add(Constants.HttpHeader.TENANT_ID, SaasContextUtil.getTenantId());
        return execution.execute(request, body);
    }
}
